package run;

import sugges.TextFile;
import sugges.Suggestion;
import base.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.io.*;

public class MainScreen extends JFrame {
	// *************** GUI ************************//
	JPanel mainPanel = new JPanel();
	JLabel welcome = new JLabel(new ImageIcon(this.getClass().getResource(
			"/img/welcome.jpg")));
	BorderLayout borderLayout1 = new BorderLayout();
	BorderLayout borderLayout2 = new BorderLayout();
	JMenuBar jMenuBar1 = new JMenuBar();
	JMenu mPlay = new JMenu("Play");
	JMenuItem mPlay_Single = new JMenuItem("Single Player");
        JMenu mPlay_Multi = new JMenu("Multi Player");
        JMenuItem mPlay_Server = new JMenuItem("Server", new ImageIcon(this.getClass()
			.getResource("/img/server.png")));
        JMenuItem mPlay_Client = new JMenuItem("Client", new ImageIcon(this.getClass()
			.getResource("/img/client.png")));
	JMenuItem mPlay_Exit = new JMenuItem("Exit", new ImageIcon(this.getClass()
			.getResource("/img/exit.png")));
	JMenu mCreate = new JMenu("Create");
	JMenuItem mCreate_New = new JMenuItem("New", new ImageIcon(this.getClass()
			.getResource("/img/new.png")));
	JMenuItem mCreate_Save = new JMenuItem("Save", new ImageIcon(this
			.getClass().getResource("/img/save.png")));
	JMenuItem mCreate_Edit = new JMenuItem("Edit", new ImageIcon(this
			.getClass().getResource("/img/edit.png")));
	JMenu mTool = new JMenu("Tool");
	JMenuItem mTool_Sugges = new JMenuItem("Sugges", new ImageIcon(this
			.getClass().getResource("/img/sugges.png")));
	JMenuItem mTool_Export = new JMenuItem("Export", new ImageIcon(this
			.getClass().getResource("/img/export.png")));
	JMenu mHelp = new JMenu("Help");
	JMenuItem mHelp_About = new JMenuItem("About", new ImageIcon(this
			.getClass().getResource("/img/info.png")));
	JMenuItem mHelp_Use = new JMenuItem("Use", new ImageIcon(this.getClass()
			.getResource("/img/help.png")));
	JButton btnOK;
	JButton btnCancel;
	JFrame frame;
	static JFrame temp;
	JComboBox comboBox, comboBox1, comboBox2, comboBox3;

	// *************** GUI ************************//

	public static CreateScreen cc;

	// khoi tao
	public MainScreen() {
		try {
			jbInit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
		}

		temp = new MainScreen();
	}

	private void jbInit() throws Exception {
		show();
		// this.getContentPane().setBackground(SystemColor.control);
		buildMenu();
		setTitle("Javacross 2.0");
		getContentPane().setLayout(borderLayout1);
		setBounds(0, 0, 720, 720);
		setLocationRelativeTo(null);
		//setResizable(false);
		addWindowListener(new WinListener());
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		mainPanel.add(welcome);
		mainPanel.setBackground(new Color(174, 190, 212));
		this.getContentPane().add(mainPanel);
		this.setIconImage(new ImageIcon(this.getClass().getResource(
				"/img/logo.png")).getImage());
		mCreate_Save.setEnabled(false);
		setVisible(true);
		validate();

	}

	private void buildMenu() {
		setJMenuBar(jMenuBar1);
		// add menu
		jMenuBar1.add(mPlay);
		jMenuBar1.add(mCreate);
		jMenuBar1.add(mTool);
		jMenuBar1.add(mHelp);

		mPlay.add(mPlay_Single);
                mPlay.add(mPlay_Multi);
                mPlay_Multi.add(mPlay_Client);
                mPlay_Multi.add(mPlay_Server);
		mPlay.addSeparator();
		mPlay.add(mPlay_Exit);
		mCreate.add(mCreate_New);
		mCreate.addSeparator();
		mCreate.add(mCreate_Save);
		mCreate.addSeparator();
		mCreate.add(mCreate_Edit);
		mTool.add(mTool_Sugges);
		mTool.addSeparator();
		mTool.add(mTool_Export);
		mHelp.add(mHelp_About);
		mHelp.addSeparator();
		mHelp.add(mHelp_Use);
		// set menu
		jMenuBar1.setBackground(new Color(199, 223, 236));
		jMenuBar1.setBorder(BorderFactory.createLineBorder(Color.black));
                mPlay.setBackground(new Color(199, 223, 236));
                mCreate.setBackground(new Color(199, 223, 236));
                mTool.setBackground(new Color(199, 223, 236));
                mHelp.setBackground(new Color(199, 223, 236));

		// add listeners

		mPlay_Single.addActionListener(new MenuListener());
                mPlay_Server.addActionListener(new MenuListener());
                mPlay_Client.addActionListener(new MenuListener());
		mPlay_Exit.addActionListener(new MenuListener());
		mCreate_Save.addActionListener(new MenuListener());
		mCreate_Edit.addActionListener(new MenuListener());
		mCreate_New.addActionListener(new MenuListener());
		mTool_Sugges.addActionListener(new MenuListener());
		mTool_Export.addActionListener(new MenuListener());
		mHelp_About.addActionListener(new MenuListener());
		mHelp_Use.addActionListener(new MenuListener());

	}

	private void showSingle() {
		Crossword cw = new Crossword();
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(this);
		File f = chooser.getSelectedFile();

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(f));
			cw = (Crossword) ois.readObject();
			ois.close();

		} catch (Exception e) {
			System.out.print(e.getStackTrace());
			JOptionPane.showMessageDialog(null, "File không phù hợp",
					"Can't open", JOptionPane.ERROR_MESSAGE);
		}
		mainPanel.removeAll();
		mainPanel.add(new PlayScreen(cw));
		this.setBounds(0, 0, 620, 720);
		this.setLocationRelativeTo(null);
		validate();
	}

        public void showServer() {
		Crossword cw = new Crossword();
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(this);
		File f = chooser.getSelectedFile();

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(f));
			cw = (Crossword) ois.readObject();
			ois.close();

		} catch (Exception e) {
			System.out.print(e.getStackTrace());
			JOptionPane.showMessageDialog(null, "File không phù hợp",
					"Can't open", JOptionPane.ERROR_MESSAGE);
		}
		mainPanel.removeAll();
		mainPanel.add(new ServerScreen(cw));
		this.setBounds(0, 0, 750, 720);
		this.setLocationRelativeTo(null);
		validate();
	}

         private void showClient() {
		Crossword cw = new Crossword();


		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(this);
		File f = chooser.getSelectedFile();


		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(f));
			cw = (Crossword) ois.readObject();
			ois.close();

		} catch (Exception e) {
			System.out.print(e.getStackTrace());
			JOptionPane.showMessageDialog(null, "File không phù hợp",
					"Can't open", JOptionPane.ERROR_MESSAGE);
		}
		mainPanel.removeAll();
		//mainPanel.add(new ClientScreen(cw));
		this.setBounds(0, 0, 620, 720);
		this.setLocationRelativeTo(null);
		validate();
	}

	private void showCreate() {
		// mainPanel.removeAll();

		// ------------Hộp thoại chọn các thông số cho ô chữ mới
		String str[] = {"Khác" , "English", "ICT", "Lịch sử", "Khoa học", "Địa lý",
				"Giải trí"};
		Integer minute[] = { 5,6,7,8,9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
		Integer second[] = new Integer[60];
		Integer size[] = new Integer[17];

		for (int i = 0; i <= 59; i++) {
			second[i] = i;
		}

		for (int i = 0; i <= 16; i++) {
			size[i] = i + 4;
		}
		comboBox = new JComboBox(str);
		comboBox1 = new JComboBox(minute);
		comboBox2 = new JComboBox(second);
		comboBox3 = new JComboBox(size);
		comboBox1.addActionListener(new CbListener());
		frame = new JFrame("Game option");
		Box box = Box.createVerticalBox();
		box.add(Box.createVerticalStrut(15));
		Box box1 = Box.createHorizontalBox();
		box1.add(Box.createHorizontalStrut(15));
		JLabel j1 = new JLabel("Chọn chủ đề :");
		box1.add(j1);
		box1.add(Box.createHorizontalStrut(29));
		box1.add(comboBox);
		box1.add(Box.createHorizontalStrut(15));
		box.add(box1);
		box.add(Box.createVerticalStrut(15));
		Box box2 = Box.createHorizontalBox();
		box2.add(Box.createHorizontalStrut(15));
		JLabel j2 = new JLabel("Chọn kích thước: ");
		box2.add(j2);
		box2.add(Box.createHorizontalStrut(15));
		box2.add(comboBox3);
		box2.add(Box.createHorizontalStrut(15));
		box.add(box2);
		box.add(Box.createVerticalStrut(15));
		Box box3 = Box.createHorizontalBox();
		box3.add(Box.createHorizontalStrut(15));
		JLabel j3 = new JLabel("Đặt thời gian: ");
		box3.add(j3);
		box3.add(Box.createHorizontalStrut(23));
		box3.add(comboBox1);
		box3.add(Box.createHorizontalStrut(5));
		box3.add(new JLabel("m"));
		box3.add(Box.createHorizontalStrut(5));
		box3.add(comboBox2);
		box3.add(Box.createHorizontalStrut(5));
		box3.add(new JLabel("s"));
		box3.add(Box.createHorizontalStrut(15));
		box.add(box3);
		box.add(Box.createVerticalStrut(15));
		Box buttonBox = Box.createHorizontalBox();
		btnOK = new JButton("OK");
		btnCancel = new JButton("Cancel");
		buttonBox.add(btnOK);
		buttonBox.add(Box.createHorizontalStrut(20));
		buttonBox.add(btnCancel);
		box.add(buttonBox, BorderLayout.CENTER);
		box.add(Box.createVerticalStrut(15));
		frame.add(box);
		frame.setLocationRelativeTo(mainPanel);
		frame.setVisible(true);
		frame.setResizable(false);
		frame.pack();
		btnOK.addActionListener(new BtListener());
		btnCancel.addActionListener(new BtListener());
	}

	private void showSave() {
		cc.saveCrossword(null);
		cc.setDoSaveCheck(false);

	}

	private void showEdit() {
		mainPanel.removeAll();
		this.setBounds(0, 0, 720, 720);
		this.setLocationRelativeTo(null);
		mCreate_Save.setEnabled(true);
		cc = new CreateScreen();
		cc.loadCrossword(this);
		mainPanel.add(cc);

	}

	private void showSugges() {
		new Suggestion();
		validate();
	}
        private void showExport(){
            Crossword cw = new Crossword();
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(this);
		File f = chooser.getSelectedFile();

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(f));
			cw = (Crossword) ois.readObject();
			ois.close();

		} catch (Exception e) {
			System.out.print(e.getStackTrace());
			JOptionPane.showMessageDialog(null, "File không phù hợp",
					"Can't open", JOptionPane.ERROR_MESSAGE);
		}
                try{
                ArrayList words = cw.getWords();
                String cwExport="";
                String fileExport=f.getName()+".doc";
                //TextFile test = new TextFile("test.txt");
                    for (int k = 0; k < words.size(); k++) {
                            Word word = (Word) words.get(k);
                            if (k==0)
                             cwExport=cwExport.concat("Keyword : "+word.getWord().toUpperCase()+"\n"+
                                    "  Gợi ý : "+ word.getClue1()+"\n\n");
                            else{
                            cwExport=cwExport.concat(" Word "+k+" : "+word.getWord().toUpperCase()+"\n"
                                    +"-Gợi ý 1: "+word.getClue1()+"\n"
                                    +"-Gợi ý 2: "+word.getClue2()+"\n"
                                    +"-Gợi ý 3: "+word.getClue3()+"\n\n");
                            }
                    }
                TextFile.write(fileExport,cwExport);
                JOptionPane.showMessageDialog(null,"Đã Export thành công\nFile kết quả : "+fileExport);

                }
                catch (Exception ex) {
                     ex.printStackTrace();
	        }

        }

	private void showAbout() {

		JOptionPane.showMessageDialog(this, " Javacross 2.0 \n eTeamvn.com",   "About Us",
				JOptionPane.INFORMATION_MESSAGE, new ImageIcon(this.getClass()
						.getResource("/img/about.jpg")));
	}

	private void showUse() {

		JOptionPane
				.showMessageDialog(
						this,
						"------------------------ Cách chơi------------------------\n"
								+ "(*) Chọn Play > Load\n"
								+ "- Check : Kiểm tra từ vừa nhập vào\n"
								+ "- Hint  : Hiển thị từ phụ không giải được (-10đ)\n"
								+ "             Hiển thị gợi ý của từ khóa      (-20đ)\n"
								+

								"- Clue  : Mỗi lần xem thêm gợi ý bạn sẽ mất 5đ của từ đó\n"
								+ "             Dùng 1 gợi ý trả lời đúng (+15đ)\n"
								+ "- Solve : Hiển thị đáp án sau khi đã chơi xong\n"
								+ "- Finish: Kết thúc game, xem bảng tổng kết\n"
								+ "- Bonus : điểm thưởng nếu giải đúng từ khóa trước\n"
								+ "             1/4 thời gian quy định : +20đ\n"
								+ "             1/2 thời gian quy định : +10đ\n"
								+ "------------------------ Cách tạo ------------------------\n"
								+ "(*) Chọn Create > New > Chọn chủ đề\n"
								+ "- Add : có 2 cách tạo từ mới\n"
								+ "           Draw: click điểm đầu & cuối để tạo thành ô chữ \n"
								+ "           Type: nhập chữ sau đó chọn vị trí để thả ô chữ\n"
								+ "- Del : xóa từ đã chọn (ấn phím Delete để xóa ô chọn)\n"
								+ "- Find: tìm từ thích hợp từ file sugges có sẵn\n"
								+ "- Key : tạo từ khóa bằng phương pháp Draw\n"
								+ "- Clue: viết gợi ý cho các từ",
						"Hướng dẫn sử dụng", JOptionPane.INFORMATION_MESSAGE,
						new ImageIcon(this.getClass().getResource(
								"/img/instruc.gif")));

	}

	private void basicClose() {
		int i = JOptionPane.showConfirmDialog(null,
				"Bạn muốn thoát khỏi chương trình", "Confirm Action",
				JOptionPane.YES_NO_OPTION);
		if (i == JOptionPane.YES_OPTION)
			System.exit(0);
	}

	private void advanceClose() {
		if (cc != null) {
			if (cc.getDoSaveCheck()) {
				int response = JOptionPane.showConfirmDialog(null,
						"Bạn đang tạo một ô chữ \nCó muốn lưu lại không ?",
						"Save?", JOptionPane.YES_NO_CANCEL_OPTION);
				if (response == JOptionPane.YES_OPTION) {

					if (cc.saveCrossword(this)) {
						System.exit(0);
						cc.setDoSaveCheck(false);
					} else
						cc.setDoSaveCheck(true);

				} else if (response == JOptionPane.NO_OPTION) {
					System.exit(0);
				} else if (response == JOptionPane.CANCEL_OPTION) {
				}
			} else {
				basicClose();
			}
		} else {
			basicClose();
		}
	}

	class WinListener implements WindowListener {
		public void windowActivated(WindowEvent e) {
		}

		public void windowClosed(WindowEvent e) {
		}

		public void windowClosing(WindowEvent e) {
			advanceClose();
		}

		public void windowDeactivated(WindowEvent e) {
		}

		public void windowDeiconified(WindowEvent e) {
		}

		public void windowIconified(WindowEvent e) {
		}

		public void windowOpened(WindowEvent e) {
		}
	}

	class CbListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			Integer second[] = new Integer[60];
			for (int i = 0; i <= 59; i++) {
				second[i] = i;
			}
			Integer second1[] = { 0 };
			JComboBox cb = (JComboBox) e.getSource();
			int a = (Integer) cb.getSelectedItem();
			if (a == 20) {
				comboBox2.setModel(new DefaultComboBoxModel(second1));
			} else {
				comboBox2.setModel(new DefaultComboBoxModel(second));
			}
		}
	}

	class BtListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {

			if (e.getSource().equals(btnOK)) {
				frame.setVisible(false);
				mainPanel.removeAll();
				temp.setBounds(0, 0, 720, 720);
				temp.setLocationRelativeTo(null);
				String s1 = (String) comboBox.getSelectedItem();
				int size = (Integer) comboBox3.getSelectedItem();
				int min = (Integer) comboBox1.getSelectedItem();
				int sec = (Integer) comboBox2.getSelectedItem();
				cc = new CreateScreen(size, size);
				if (s1.equals("English")) {
					cc.setTheme(1);
				} else if (s1.equals("ICT")) {
					cc.setTheme(2);

				} else if (s1.equals("Lịch sử")) {
					cc.setTheme(3);
				} else if (s1.equals("Khoa học")) {
					cc.setTheme(5);
				} else if (s1.equals("Địa lý")) {
					cc.setTheme(4);
				} else if (s1.equals("Giải trí")) {
					cc.setTheme(6);
				} else if (s1.equals("Khác")) {
					cc.setTheme(7);
				}
				cc.setTime(min, sec);
				cc.setDoSaveCheck(true);
				mCreate_Save.setEnabled(true);
				mainPanel.add(cc);
				validate();

			} else {
				frame.setVisible(false);
			}
		}
	}

	class MenuListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {

			if (e.getSource().equals(mPlay_Single)) {
				showSingle();
			} else if (e.getSource().equals(mPlay_Server)) {
				showServer();
                        } else if (e.getSource().equals(mPlay_Client)) {
				Login.main(null);
                        } else if (e.getSource().equals(mPlay_Exit)) {
                                advanceClose();
			} else if (e.getSource().equals(mCreate_New)) {
				showCreate();
			} else if (e.getSource().equals(mCreate_Edit)) {
				showEdit();
			} else if (e.getSource().equals(mCreate_Save)) {
				showSave();
			} else if (e.getSource().equals(mTool_Sugges)) {
				showSugges();
                        } else if (e.getSource().equals(mTool_Export)) {
				showExport();
			} else if (e.getSource().equals(mHelp_About)) {
				showAbout();
			} else if (e.getSource().equals(mHelp_Use)) {
				showUse();
			}
			validate();
		}
	}
}
